<?php

class ZoneController extends Controller {
    
    public $class = 'chauffage';


    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
	  $model = $this->loadModel($id);

	  if (isset($_POST['Zone'])) {
		$model->attributes = $_POST['Zone'];
		if (isset($_POST['Horaire'])) {
		    $model->horaires = $_POST['Horaire'];
		    $model->saveWithRelated('horaires');
		}
		if ($model->save()) {
		    $this->redirect(array('/chauffage/'));
		}
	  }

	  $this->render('update', array(
		'model' => $model,
	  ));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
	  $dataProvider = new CActiveDataProvider('Zone');
	  $this->render('control', array(
		'dataProvider' => $dataProvider,
	  ));
    }

    /**
     * Lists all models.
     */
    public function actionControl() {
	  $dataProvider = new CActiveDataProvider('Zone');

	  // Si demande de POST (via Ajax), on enregistre les modifs
	  if (isset($_POST['Zone'])) {
		

		$retour = '';
		
		// On passe en revue chaque zone
		$zones = $dataProvider->getData();
		foreach ($zones as $zone) {

		    if (isset($_POST['Zone'][$zone->id])) {
			  
			  // Enregistrement de la zone uniquement si elle est modifiée
			  if ($_POST['Zone'][$zone->id]['modeid'] != $zone->modeid) {
				
				$zone->modeid = $_POST['Zone'][$zone->id]['modeid'];
				$retour .= $zone->save() ? 'Zone "'.$zone->nom.'" modifiée' : 'Erreur sur '. $zone->nom;
			  }
		    }
		}

		print_r($retour);
		return;
	  }

	  $this->render('control', array(
		'dataProvider' => $dataProvider,
	  ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Zone the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
	  $model = Zone::model()->findByPk($id);
	  if ($model === null)
		throw new CHttpException(404, 'The requested page does not exist.');
	  return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Zone $model the model to be validated
     */
    protected function performAjaxValidation($model) {
	  if (isset($_POST['ajax']) && $_POST['ajax'] === 'zone-form') {
		echo CActiveForm::validate($model);
		Yii::app()->end();
	  }
    }

    public function actionAddHoraireByAjax($index, $periodeid) {
	  $model = new Horaire;
	  $model->periodeid = $periodeid;
	  $this->renderPartial('/horaire/_form', array(
		'model' => $model,
		'index' => $index,
	  ));
    }

}
